<?php

/**
 * Description of ReportController
 * 
 * @author trongkhoi
 * @since Jun 28, 2013 - 10:00:41 AM
 */
class ReportController extends MyController
{

    public function actionSale()
    {
        $select_merchant   = (isset($_GET['business']) && $_GET['business'] !== 0) ? $_GET['business'] : "";
        $select_staff      = (isset($_GET['staff']) && $_GET['staff'] !== 0) ? $_GET['staff'] : "";
        $start_date        = isset($_GET['start_date']) ? $_GET['start_date'] : '0';
        $end_date          = isset($_GET['end_date']) ? $_GET['end_date'] : '0';
        $criteria          = new CDbCriteria();
        $criteria1         = new CDbCriteria();
        $criteria1->select = "t.*";
        $date_type         = '';
        if (!empty($start_date) && $start_date != '0')
        {
            if (!empty($end_date) && $end_date != '0')
            {
                $start     = strtotime(str_replace('/', '-', $start_date));
                $end       = strtotime(str_replace('/', '-', $end_date));
                $date_type = 'between';
                //$criteria1->addBetweenCondition('t.receipt_date', $start, $end);
            }
            else
            {
                $start     = strtotime(str_replace('/', '-', $start_date));
                $date_type = 'start';
                //$criteria1->addCondition("t.receipt_date>='".$start."'");
            }
        }
        else
        {
            if (!empty($end_date) && $end_date != '0')
            {
                $date_type = 'end';
                $end       = strtotime(str_replace('/', '-', $end_date));
                //$criteria1->addCondition("t.receipt_date<='".$end."'");
            }
        }



        if ($this->isBussiness)
        {
            $criteria->with  = array('order', 'order.appoint');
            $criteria1->with = array('order', 'order.appoint');
            if ($this->isBranch)
            {
                $arr_author = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId(), FALSE);
                $criteria->addInCondition('appoint.author_id', $arr_author);
                $criteria1->addInCondition('appoint.author_id', $arr_author);
            }
            else//Root Merchant
            {
                $curr_user        = Yii::app()->user->currentUser;
                $root_merchant_id = $curr_user->author_id;
                $staff_root       = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId(), FALSE);
                $staff_branch     = Merchant::getAllStaffIdOfBranch($root_merchant_id);
                $total_merchant   = $staff_root + $staff_branch;
                array_push($total_merchant, $curr_user->id);
                $criteria->addInCondition('appoint.author_id', $total_merchant);
                $criteria1->addInCondition('appoint.author_id', $total_merchant);
            }
        }
        if ($select_merchant != '0' && $select_merchant != '')
        {

            $biz_id          = Users::getIdByUkey($select_merchant);
            $arr_author      = Users::getAllStaffUkeyByBizUkey($biz_id, FALSE);
            array_push($arr_author, $biz_id);
            $criteria1->with = array('order', 'order.appoint');
            $criteria1->addInCondition('appoint.author_id', $arr_author);
        }

        if ($select_staff != '0' && $select_staff != "")
        {
            $staff_id        = Users::getIdByUkey($select_staff);
            $criteria1->with = array('order', 'order.appoint');
            $criteria1->addCondition("appoint.author_id=$staff_id");
        }
        $criteria1->join     = "INNER JOIN {{orders}} t2 on t2.order_id = `t`.order_id";
        $arr_order           = Receipt::model()->findAll($criteria1);
        $totalPrice          = 0;
        $totalDiscount       = 0;
        $totalTax            = 0;
        $totalCash           = 0;
        $totalPaypal         = 0;
        $totalCredit         = 0;
        $totalPackageSession = 0;
        $totalPackage        = 0;
        $totalRetail         = 0;
        $totalDiscountRetail = 0;
        $totalOrder          = 0;
        $curYear             = date('Y');
        $curMonth            = date('m');
        $arr_year            = array();
        if ($curMonth < 6)
        {
            $month_last = 6 - $curMonth;
            $month      = 12;
            for ($i = 1; $i <= $month_last; $i++)
            {
                $arr_year_          = array();
                $arr_year_['year']  = $curYear - 1;
                $arr_year_['month'] = $month;
                $arr_year_['start'] = strtotime($arr_year_['year'] . '-' . $month . '-01 00:00:00');
                $dayofMonth         = Helper::getDayofMonth($month, $arr_year_['year']);
                $arr_year_['end']   = strtotime($arr_year_['year'] . '-' . $month . '-' . $dayofMonth . ' 00:00:00');
                $arr_year_['total'] = 0;
                $arr_year_['count'] = 0;
                $month--;
                array_push($arr_year, $arr_year_);
            }
            for ($i = 1; $i <= $curMonth; $i++)
            {
                $arr_year_          = array();
                $arr_year_['year']  = $curYear;
                $arr_year_['month'] = $i;
                $arr_year_['start'] = strtotime($arr_year_['year'] . '-' . $i . '-01 00:00:00');
                $dayofMonth         = Helper::getDayofMonth($i, $arr_year_['year']);
                $arr_year_['end']   = strtotime($arr_year_['year'] . '-' . $i . '-' . $dayofMonth . ' 00:00:00');
                $arr_year_['total'] = 0;
                $arr_year_['count'] = 0;
                array_push($arr_year, $arr_year_);
            }
        }
        else
        {
            for ($i = ($curMonth - 6); $i <= $curMonth; $i++)
            {
                $arr_year_          = array();
                $arr_year_['year']  = $curYear;
                $arr_year_['month'] = $i;
                $arr_year_['start'] = strtotime($arr_year_['year'] . '-' . $i . '-01 00:00:00');
                $dayofMonth         = Helper::getDayofMonth($i, $arr_year_['year']);
                $arr_year_['end']   = strtotime($arr_year_['year'] . '-' . $i . '-' . $dayofMonth . ' 00:00:00');
                $arr_year_['total'] = 0;
                $arr_year_['count'] = 0;
                array_push($arr_year, $arr_year_);
            }
        }
        $totalChart = 0;
        if ($arr_order != NULL)
        {
            foreach ($arr_order as $v)
            {
                $set = false;
                if ($date_type == '')
                    $set = true;
                elseif ($date_type == 'between')
                {
                    if ($v->receipt_date >= $start && $v->receipt_date <= $end)
                        $set = true;
                }elseif ($date_type == 'start')
                {
                    if ($v->receipt_date >= $start)
                        $set = true;
                }elseif ($date_type == 'end')
                {
                    if ($v->receipt_date <= $end)
                        $set = true;
                }
                $retail_receipt_price    = 0;
                $retail_receipt_discount = 0;
                if (@$v->order->retailOrder && $v->order->retailOrder->receipt)
                {
                    $retail_receipt_price    = $v->order->retailOrder->receipt->final_price;
                    $retail_receipt_discount = $v->order->retailOrder->receipt->discount_type == '%' ?
                            $v->order->retailOrder->total_price * $v->order->retailOrder->receipt->discount :
                            $v->order->retailOrder->receipt->discount;
                }
                $discount = @$v->discount_type == '$' ? $v->discount : @$v->order->s_price * $v->discount / 100;
                if ($set == true)
                {
                    $totalPrice+=@$v->order->s_price;
                    $totalDiscount+=$discount;
                    $totalTax+=@$v->tax;
                    $totalCash += @$v->order->payment_method == Orders::PAYMENT_CASH ? @$v->order->service->price + @$gst : 0;
                    $totalPaypal += @$v->order->payment_method == Orders::PAYMENT_PAYPAL ? @$v->order->service->price + @$gst : 0;
                    $totalCredit += @$v->order->payment_method == Orders::PAYMENT_CREDIT ? @$v->order->service->price + @$gst : 0;
                    $totalPackageSession += @$v->order->packageOrder ? 1 : 0;
                    $totalPackage += @$v->order->packageOrder ? $pack_revenue : 0;
                    $totalRetail += $retail_receipt_price;
                    $totalDiscountRetail += $retail_receipt_discount;
                }
                foreach ($arr_year as $key => $value)
                {
                    if ($v->receipt_date >= $value['start'] && $v->receipt_date <= $value['end'])
                    {
                        $arr_year[$key]['total'] += @$v->order->s_price + @$v->tax - $discount + $retail_receipt_price - $retail_receipt_discount;
                        $totalChart+=$arr_year[$key]['total'];
                        $arr_year[$key]['count'] ++;
                    }
                }
            }
        }

        $chart_str = "";
        if (!empty($arr_year))
        {
            foreach ($arr_year as $year_)
            {
                if ($chart_str == "")
                    $chart_str.="['" . $year_['month'] . '/' . $year_['year'] . "', " . $year_['total'] . "," . $year_['count'] . "]";
                else
                    $chart_str.=", ['" . $year_['month'] . '/' . $year_['year'] . "', " . $year_['total'] . "," . $year_['count'] . "]";
            }
        }
        $totalOrder = $totalPrice + $totalTax - $totalDiscount + $totalRetail - $totalDiscountRetail;
//        $criteria->select = "SUM(t2.s_price) as totalPrice,SUM(CASE WHEN discount_type='$' THEN discount ELSE 0 END) as totalDiscount, SUM(CASE WHEN discount_type='%' THEN discount*t2.s_price/100 ELSE 0 END) as totalDiscount2, SUM(`t`.tax) as totalTax";
//        $criteria->join = "INNER JOIN {{orders}} t2 on t2.order_id = `t`.order_id";
//        $totalReport = Receipt::model()->find($criteria);

        $cri        = new CDbCriteria();
        $cri->order = 't.receipt_date DESC';
        if (!empty($start_date) && $start_date != '0')
        {
            if (!empty($end_date) && $end_date != '0')
            {
                $start = strtotime(str_replace('/', '-', $start_date));
                $end   = strtotime(str_replace('/', '-', $end_date));
                $cri->addBetweenCondition('t.receipt_date', $start, $end);
            }
            else
            {
                $start = strtotime(str_replace('/', '-', $start_date));
                $cri->addCondition("t.receipt_date>='" . $start . "'");
            }
        }
        else
        {
            if (!empty($end_date) && $end_date != '0')
            {
                $end = strtotime(str_replace('/', '-', $end_date));
                $cri->addCondition("t.receipt_date<='" . $end . "'");
            }
        }

        if ($this->isBussiness)
        {
            $cri->with = array('order', 'order.appoint');
            if ($this->isBranch)
            {
                $arr_author = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId(), FALSE);
                $cri->addInCondition('appoint.author_id', $arr_author);
            }
            else//Root Merchant
            {
                $curr_user        = Yii::app()->user->currentUser;
                $root_merchant_id = $curr_user->author_id;
                $staff_root       = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId(), FALSE);
                $staff_branch     = Merchant::getAllStaffIdOfBranch($root_merchant_id);
                $total_merchant   = $staff_root + $staff_branch;
                array_push($total_merchant, $curr_user->id);
                $cri->addInCondition('appoint.author_id', $total_merchant);
            }
        }

        if ($this->isStaff)
        {
            $cri->with = array('order', 'order.appoint');
            $cri->compare('appoint.author_id', Yii::app()->user->getId());
        }
        if ($select_merchant != '0' && $select_merchant != '')
        {

            $biz_id     = Users::getIdByUkey($select_merchant);
            $arr_author = Users::getAllStaffUkeyByBizUkey($biz_id, FALSE);
            array_push($arr_author, $biz_id);
            $cri->with  = array('order', 'order.appoint');
            $cri->addInCondition('appoint.author_id', $arr_author);
        }
        if ($select_staff != '0' && $select_staff != "")
        {
            $staff_id  = Users::getIdByUkey($select_staff);
            $cri->with = array('order', 'order.appoint');
            $cri->addCondition("appoint.author_id=$staff_id");
        }
        $cri->join = "INNER JOIN {{orders}} t2 on t2.order_id = `t`.order_id";

        $count           = Receipt::model()->count($cri);
        $pages           = new CPagination($count);
        $pages->route    = "report/sale";
        $pages->pageSize = 100;
        $pages->applyLimit($cri);
        $receipts        = Receipt::model()->findAll($cri);
        $this->render('sale', array(
            'pages'               => $pages,
            'receipts'            => $receipts,
            'totalPrice'          => $totalPrice,
            'totalDiscount'       => $totalDiscount,
            'totalTax'            => $totalTax,
            'totalCash'           => $totalCash,
            'totalPaypal'         => $totalPaypal,
            'totalCredit'         => $totalCredit,
            'totalPackageSession' => $totalPackageSession,
            'totalPackage'        => $totalPackage,
            'totalRetail'         => $totalRetail,
            'totalDiscountRetail' => $totalDiscountRetail,
            'totalOrder'          => $totalOrder,
            'select_merchant'     => $select_merchant,
            'select_staff'        => $select_staff,
            'chart_str'           => $chart_str,
                )
        );
    }

    public function actionGetOrdersByStaff()
    {
        $start_date = $_POST['start_date'];
        $end_date   = $_POST['end_date'];
        $data       = $this->getlist_orders_with_page($start_date, $end_date);
        $receipts   = $data ? $data['receipts'] : NULL;
        $pages      = $data ? $data['pages'] : NULL;
        echo $this->renderPartial('_sale', array(
            'pages'    => $pages,
            'receipts' => $receipts
        ));
        Yii::app()->end();
    }

    private function getlist_orders_with_page($start_date = NULL, $end_date = NULL)
    {

        $criteria1         = new CDbCriteria();
        $criteria1->select = "t.*";
        if ($start_date != '0' && $end_date != '0')
        {
            $start = strtotime(str_replace('/', '-', $start_date));
            $end   = strtotime(str_replace('/', '-', $end_date));
            $criteria1->addBetweenCondition('t.receipt_date', $start, $end);
        }
        if ($this->isBussiness)
        {
            $criteria->with  = array('order', 'order.appoint');
            $criteria1->with = array('order', 'order.appoint');
            if ($this->isBranch)
            {
                $arr_author = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId(), FALSE);
                $criteria->addInCondition('appoint.author_id', $arr_author);
                $criteria1->addInCondition('appoint.author_id', $arr_author);
            }
            else//Root Merchant
            {
                $curr_user        = Yii::app()->user->currentUser;
                $root_merchant_id = $curr_user->author_id;
                $staff_root       = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId(), FALSE);
                $staff_branch     = Merchant::getAllStaffIdOfBranch($root_merchant_id);
                $total_merchant   = $staff_root + $staff_branch;
                $criteria->addInCondition('appoint.author_id', $total_merchant);
                $criteria1->addInCondition('appoint.author_id', $total_merchant);
            }
        }
        $criteria1->join     = "INNER JOIN {{orders}} t2 on t2.order_id = `t`.order_id";
        $arr_order           = Receipt::model()->findAll($criteria1);
        $totalPrice          = 0;
        $totalDiscount       = 0;
        $totalTax            = 0;
        $totalCash           = 0;
        $totalPaypal         = 0;
        $totalCredit         = 0;
        $totalPackageSession = 0;
        $totalPackage        = 0;
        $totalRetail         = 0;
        $totalDiscountRetail = 0;
        $totalOrder          = 0;
        if ($arr_order != NULL)
        {
            foreach ($arr_order as $v)
            {
                $retail_receipt_price    = 0;
                $retail_receipt_discount = 0;
                if (@$v->order->retailOrder && $v->order->retailOrder->receipt)
                {
                    $retail_receipt_price    = $v->order->retailOrder->receipt->final_price;
                    $retail_receipt_discount = $v->order->retailOrder->receipt->discount_type == '%' ?
                            $v->order->retailOrder->total_price * $v->order->retailOrder->receipt->discount :
                            $v->order->retailOrder->receipt->discount;
                }
                $discount = @$v->discount_type == '$' ? $v->discount : @$v->order->s_price * $v->discount / 100;
                $totalPrice+=@$v->order->s_price;
                $totalDiscount+=$discount;
                $totalTax+=@$v->tax;
                $totalCash += @$v->order->payment_method == Orders::PAYMENT_CASH ? @$v->order->service->price + @$gst : 0;
                $totalPaypal += @$v->order->payment_method == Orders::PAYMENT_PAYPAL ? @$v->order->service->price + @$gst : 0;
                $totalCredit += @$v->order->payment_method == Orders::PAYMENT_CREDIT ? @$v->order->service->price + @$gst : 0;
                $totalPackageSession += @$v->order->packageOrder ? 1 : 0;
                $totalPackage += @$v->order->packageOrder ? $pack_revenue : 0;
                $totalRetail += $retail_receipt_price;
                $totalDiscountRetail += $retail_receipt_discount;
            }
        }
        $totalOrder                         = $totalPrice + $totalTax - $totalDiscount + $totalRetail - $totalDiscountRetail;
        $orderDetail                        = array();
        $orderDetail['totalOrder']          = $totalOrder;
        $orderDetail['totalPrice']          = $totalPrice;
        $orderDetail['totalDiscount']       = $totalDiscount;
        $orderDetail['totalTax']            = $totalTax;
        $orderDetail['totalCash']           = $totalCash;
        $orderDetail['totalPaypal']         = $totalPaypal;
        $orderDetail['totalCredit']         = $totalCredit;
        $orderDetail['totalPackageSession'] = $totalPackageSession;
        $orderDetail['totalPackage']        = $totalPackage;
        $orderDetail['totalRetail']         = $totalRetail;
        $orderDetail['totalDiscountRetail'] = $totalDiscountRetail;

        $criteria        = new CDbCriteria();
        $criteria->order = 't.receipt_date DESC';
        if ($start_date != '0' && $end_date != '0')
        {
            $start = strtotime(str_replace('/', '-', $start_date));
            $end   = strtotime(str_replace('/', '-', $end_date));
            $criteria->addBetweenCondition('t.receipt_date', $start, $end);
        }
        $criteria->with = array('order', 'order.appoint');
        if (isset($_POST['biz_ukey']))
        {
            if ($_POST['biz_ukey'] != '0')
            {

                $biz_id     = Users::getIdByUkey($_POST['biz_ukey']);
                $arr_author = Users::getAllStaffUkeyByBizUkey($biz_id, FALSE);

                $criteria->addInCondition('appoint.author_id', $arr_author);
            }
        }

        if ($this->isBussiness)
        {
            $arr_author = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId(), FALSE);
            $criteria->addInCondition('appoint.author_id', $arr_author);
        }
        if ($this->isStaff)
        {
            $criteria->compare('appoint.author_id', Yii::app()->user->getId());
        }

        if (isset($_POST['staff_ukey']))
        {
            if ($_POST['staff_ukey'] != '0')
            {
                $staff_id = Users::getIdByUkey($_POST['staff_ukey']);
                $criteria->addCondition("appoint.author_id=$staff_id");
            }
        }
        $criteria->join = "INNER JOIN {{orders}} t2 on t2.order_id = `t`.order_id";

        $count           = Receipt::model()->count($criteria);
        $pages           = new CPagination($count);
        $pages->route    = "report/sale";
        $pages->pageSize = 50;
        $pages->applyLimit($criteria);
        $receipts        = Receipt::model()->findAll($criteria);

        if ($receipts == NULL)
        {
            return FALSE;
        }

        return array(
            'receipts'    => $receipts,
            'pages'       => $pages,
            'orderDetail' => $orderDetail,
        );
    }

    private function getlist_orders($start_date = '0', $end_date = '0')
    {

        $criteria        = new CDbCriteria();
        $criteria->order = 't.receipt_date DESC';
        if ($start_date != '0' && $end_date != '0')
        {
            $start = strtotime(str_replace('/', '-', $start_date));
            $end   = strtotime(str_replace('/', '-', $end_date));
            $criteria->addBetweenCondition('t.receipt_date', $start, $end);
        }
        $criteria->with = array('order', 'order.appoint');
        if (isset($_POST['biz_ukey']))
        {
            if ($_POST['biz_ukey'] != '0' && $_POST['biz_ukey'] != '')
            {

                $biz_id     = Users::getIdByUkey($_POST['biz_ukey']);
                $arr_author = Users::getAllStaffUkeyByBizUkey($biz_id, FALSE);

                $criteria->addInCondition('appoint.author_id', $arr_author);
            }
        }

        if ($this->isBussiness)
        {
            $arr_author = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId(), FALSE);
            $criteria->addInCondition('appoint.author_id', $arr_author);
        }
        if ($this->isStaff)
        {
            $criteria->compare('appoint.author_id', Yii::app()->user->getId());
        }

        if (isset($_POST['staff_ukey']))
        {
            if ($_POST['staff_ukey'] != '0')
            {
                $staff_id = Users::getIdByUkey($_POST['staff_ukey']);
                $criteria->addCondition("appoint.author_id=$staff_id");
            }
        }

        $receipts = Receipt::model()->findAll($criteria);

        if ($receipts == NULL)
        {
            return FALSE;
        }

        return $receipts;
    }

    public function actionExport()
    {
//        $biz_name = '';

        $fileName = "Report_sales.csv";
        header('Content-Encoding: UTF-8');
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header('Content-type: text/csv; charset=UTF-8');
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");

        $fh     = @fopen('php://output', 'w');
        $header = array(
            '#',
            'Order date',
            'Apt Date',
            'Account Code',
            'Account Name',
            'Company',
            'Service Name',
            'Price',
            'GST',
            'Discount',
            'Cash',
            'Paypal',
            'Credit Card',
            'NETS',
            'Package sessions used',
            'Package Revenue',
            'Retail Revenue',
            'Retail Discount',
            'Person in Charge',
            'Customer',
            'Branch',
        );
        fputcsv($fh, $header);

        $total_price           = 0;
        $total_tax             = 0;
        $total_discount        = 0;
        $total_cash            = 0;
        $total_paypal          = 0;
        $total_credit          = 0;
        $total_package_session = 0;
        $total_package         = 0;
        $total_retail          = 0;
        $total_discount_retail = 0;
        $receipts              = $this->getlist_orders((isset($_POST['le_start_date']) ? $_POST['le_start_date'] : 0), (isset($_POST['le_end_date']) ? $_POST['le_end_date'] : 0));

        foreach ($receipts as $i => $v)
        {
            $data   = array();
            $data[] = $i + 1;
            $data[] = date('d/M/Y', @$v->order->order_date);
            $data[] = date('d/M/Y', @$v->order->appoint->date);

            $data[] = '';
            $data[] = '';

            if (isset($v->order->merchant))
            {
                $data[] = $v->order->merchant->isBranch ? $v->order->merchant->author->name : $v->order->merchant->name;
            }
            else
            {
                $data[] = @$v->order->service->user->name;
            }
            $data[] = @$v->order->service->s_name;
            $data[] = '$' . @$v->order->s_price;
            $data[] = $v->tax . ' (' . @$v->order->tax / 100 . '%)';

            $discount = @$v->discount_type == '$' ? $v->discount : @$v->order->s_price * $v->discount / 100;
            $data[]   = $discount;

            $data[] = @$v->order->payment_method == Orders::PAYMENT_CASH ? '$' . @$v->final_price : '';
            $data[] = @$v->order->payment_method == Orders::PAYMENT_PAYPAL ? '$' . @$v->final_price : '';
            $data[] = @$v->order->payment_method == Orders::PAYMENT_CREDIT ? '$' . @$v->final_price : '';
            $data[] = '';
            $data[] = @$v->order->packageOrder ? '1' : '';

            if (isset($v->order->packageOrder))
            {
                $pack         = $v->order->packageOrder->packageCustomer->package;
                $pack_revenue = $pack->price / $pack->limit;
            }
            else
            {
                $pack_revenue = '';
            }

            $data[]                  = $pack_revenue != '' ? '$' . $pack_revenue : $pack_revenue;
            //Retail
            $retail_receipt          = 0;
            $retail_receipt_discount = 0;
            if (isset($v->order->retailOrder))
            {
                echo '$';
                $retail_receipt          = $v->order->retailOrder->receipt ? $v->order->retailOrder->receipt->final_price : 0;
                $retail_receipt_discount = $v->order->retailOrder->receipt->discount_type == '%' ?
                        $v->order->retailOrder->total_price * $v->order->retailOrder->receipt->discount :
                        $v->order->retailOrder->receipt->discount;
            }
            $data[] = $retail_receipt;
            $data[] = $retail_receipt_discount;
            $data[] = @$v->order->staffsPerform;
            $data[] = @$v->order->customer->name;
            $data[] = @$v->order->merchant->isBranch ? $v->order->merchant->name : '';
            fputcsv($fh, $data);

            //Total value
            $total_price+=@$v->order->s_price;
            $total_tax+=@$v->tax;
            $total_discount+=$discount;
            $total_cash += @$v->order->payment_method == Orders::PAYMENT_CASH ? @$v->final_price : 0;
            $total_paypal += @$v->order->payment_method == Orders::PAYMENT_PAYPAL ? @$v->final_price : 0;
            $total_credit += @$v->order->payment_method == Orders::PAYMENT_CREDIT ? @$v->final_price : 0;
            $total_package_session += @$v->order->packageOrder ? 1 : 0;
            $total_package += @$v->order->packageOrder ? $pack_revenue : 0;
            $total_retail += $retail_receipt;
            $total_discount_retail += $retail_receipt_discount;
        }

        //Total
        $total = array('Total:', '', '', '', '', '', '', "$$total_price", "$$total_tax", "$total_discount", "$$total_cash",
            "$$total_paypal", "$$total_credit", '', "$total_package_session", "$$total_package", "$$total_retail", "$$total_discount_retail", '', '', '');
        fputcsv($fh, $total);
// Close the file
        fclose($fh);
// Make sure nothing else is sent, our file is done
        exit;
    }

}

/**
 * End of ReportController
 */
